﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CNVP.JShop.UI;
using CNVP.Config;
using CNVP.Framework.Utils;
using CNVP.JShop.Web.WebReference;
using System.Threading;

namespace CNVP.JShop.Web.Admin
{
    public partial class UpdateManger : AdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!BLL.BLLCheckAdmin.LoginOk(Page, 100)) return;//判断页面权限
            IndexWS webServer = new IndexWS();
            string productName = LicenseConfig.ProductName;
            string productVersion = LicenseConfig.ProductVersion;
            String getAction = Request.Params["action"];
            DateTime publishDate = Convert.ToDateTime(LicenseConfig.PostTime);
            bool hasNewPatch = false;
            try
            {
                hasNewPatch = webServer.HasNewestPatch(productName, publishDate);
            }
            catch
            {
            }
            if (hasNewPatch)
            {
                if (String.IsNullOrEmpty(getAction) || Convert.ToString(getAction).ToLower() != "update")
                {
                    litInfo.Text = "<span style='color:red;'>（有更新）</span>";
                    litAction.Text = "<a href='?action=update'>更新</a>";
                }
                else
                {
                    String newestPatchName = "";
                    newestPatchName = webServer.GetLatestPatchName(productName);
                    string patchFile = String.Empty;
                    patchFile = webServer.GetPatchPackUrl(productName, publishDate);
                    if (!String.IsNullOrEmpty(patchFile))
                    {
                        if (patchFile.Substring(1, 7) == "\"error\"")
                        {
                            if (patchFile.Length > 8)
                            {
                                String r = patchFile.Substring(9);
                                MessageUtils.ShowPre(r.Remove(r.Length - 1));
                            }
                            else
                            {
                                MessageUtils.ShowPre("出现错误。");
                            }
                        }
                        else
                        {
                            Server.ScriptTimeout = 999999999;
                            string LocalUrl = Server.MapPath(@"/Config/Cache/patch.zip");
                            string LocalFolder = Server.MapPath(@"/Config/Cache/TempFile/");
                            string SqlFolder = Server.MapPath(@"/Config/Cache/TempFile/Patch/Patch/");
                            string jsBlock = String.Empty;
                            Response.Clear();
                            Public.RewriteHTML();

                            Public.DownloadFile(webServer.Url.Substring(0, webServer.Url.LastIndexOf(@"/") + 1) + patchFile, LocalUrl, "正在下载安装文件...");
                            Thread.Sleep(500);
                            jsBlock = "<script" + ">BeginTrans('文件下载操作完成，正在执行更新操作...');<" + "/script>";
                            Response.Write(jsBlock);
                            Response.Flush();

                            Thread.Sleep(500);

                            using (FileStream fs = File.Open(LocalUrl, FileMode.Open))
                            {
                                //解压缩到临时文件夹
                                ZipClass.ExtractZip(fs, LocalFolder);
                                //执行更新程序
                                Public.DataUpdate(SqlFolder);
                                //拷贝相关文件
                                FileUtils.CopyFolder(LocalFolder + "Patch/Patch/Patch/", Server.MapPath("~/"));
                            }
                            jsBlock = "<script" + ">BeginTrans('模块更新操作成功。...');<" + "/script>";
                            Response.Write(jsBlock);
                            Response.Flush();

                            Thread.Sleep(500);
                            FileUtils.DeleteFile(LocalUrl);
                            FileUtils.DeleteFolder(LocalFolder);

                            Config.BaseConfig.SaveXmlConfig("ProductVersion", newestPatchName);

                            Config.BaseConfig.SaveXmlConfig("PostTime", DateTime.Now.ToString());
                            Config.LicenseConfig.RefurbishCatch();
                            Config.VerConfig.SaveXmlConfig("Version", newestPatchName);
                            Config.VerConfig.SaveXmlConfig("PubTime", DateTime.Now.ToString("yyyy-MM-dd"));
                            jsBlock = "<script" + ">EndTrans('临时文件删除操作成功。');<" + "/script>";
                            Response.Write(jsBlock);
                            Response.Flush();

                            Thread.Sleep(500);
                            Response.Clear();

                            Response.Write("<script type=\"text/javascript\">window.history.go(-1);</script>");
                            Response.End();
                        }
                    }
                }
            }
        }
    }
}
